package com.nekonomics
package persistence.query

import domain.detail.OrderItemDetail

import doobie.*
import doobie.implicits.*
import doobie.postgres.implicits.*
import zio.{ULayer, ZLayer}

trait OrderItemDetailRepo {
  def listByUserId(userId: Long): ConnectionIO[List[OrderItemDetail]]

  def listByOrderId(orderId: Long): ConnectionIO[List[OrderItemDetail]]
}

object OrderItemDetailRepo {
  val live: ULayer[OrderItemDetailRepo] = ZLayer.succeed(OrderItemDetailRepoLive)
}


object OrderItemDetailRepoLive extends OrderItemDetailRepo {

  val baseSql =
    sql"""
         |select
         |  "order".id,
         |  sku.id,
         |  spu.id,
         |  merchant.id,
         |  merchant.name,
         |  merchant.logo,
         |  spu.name,
         |  order_item.quantity,
         |  order_item.price_at_purchase,
         |  "order".created_at,
         |  "order".status,
         |  sku.image_url
         |from public.order_item
         |join public.order on order_item.order_id  = "order".id
         |join public.sku   on order_item.sku_id    = sku.id
         |join public.spu   on sku.spu_id           = spu.id
         |join public.merchant on spu.merchant_id   = merchant.id
         """.stripMargin


  override def listByUserId(userId: Long): doobie.ConnectionIO[List[OrderItemDetail]] = {
    (baseSql ++ fr"""where "order".user_id = $userId""")
      .query[OrderItemDetail]
      .to[List]

  }

  override def listByOrderId(orderId: Long): doobie.ConnectionIO[List[OrderItemDetail]] = {
    (baseSql ++ fr"""where  "order".id = $orderId  """)
      .query[OrderItemDetail]
      .to[List]
  }
}